package com.biter.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import net.sf.json.JSONObject;

import com.biter.config.ConfigDef;
import com.wanpu.pay.PayConnect;
import com.wanpu.pay.PayResultListener;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class Util {

	/**
	 * 获得网络数据
	 * @param path
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public static String getHtml(String path, String encoding) throws Exception {
		String return_val = "";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(6 * 1000);
		if (conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			byte[] data = readStream(inputStream);
			return_val = new String(data, encoding);
		}
		if(path.indexOf("mtgox.com")>0){
			JSONObject newObject = new JSONObject();
			JSONObject tickerObject = new JSONObject();
			JSONObject object = JSONObject.fromObject(return_val);
			JSONObject data = object.getJSONObject("data");
			JSONObject high = data.getJSONObject("high");
			String highvalue = String.valueOf(high.get("display"));
			tickerObject.put("high", highvalue.substring(1));
			JSONObject low = data.getJSONObject("low");
			String lowvalue = String.valueOf(low.get("display"));
			tickerObject.put("low", lowvalue.substring(1));
			JSONObject buy = data.getJSONObject("buy");
			String buyvalue = String.valueOf(buy.get("display"));
			tickerObject.put("buy", buyvalue.substring(1));
			JSONObject sell = data.getJSONObject("sell");
			String sellvalue = String.valueOf(sell.get("display"));
			tickerObject.put("sell", sellvalue.substring(1));
			JSONObject last = data.getJSONObject("last");
			String lastvalue = String.valueOf(last.get("display"));
			tickerObject.put("last", lastvalue.substring(1));
			JSONObject vol = data.getJSONObject("vol");
			String volvalue = String.valueOf(vol.get("value"));
			tickerObject.put("vol", volvalue.substring(0, volvalue.indexOf(".")+2));
			newObject.put("ticker", tickerObject);
			return_val = newObject.toString();
		}
		
		return return_val;
	}

	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outstream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outstream.write(buffer, 0, len);
		}
		outstream.close();
		inStream.close();

		return outstream.toByteArray();
	}

	
	public static boolean isServiceRunning(Context context,String ServiceName) {
		ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString().equals(ServiceName)) {
				return true;
			}
		}
		return false;
	}
	
	
	public static void show_pay(Context context) {
		java.util.Date dt = new Date();
		String orderId = String.valueOf(dt.getTime());
		String userId = PayConnect.getInstance(context).getDeviceId(context);
		float price = ConfigDef.PAY_FOR_AD;
		String goodsName = "购买去广告服务";
		String goodsDesc = "购买该服务之后，一个月内不在出现广告!";
		MyPayResultListener mpr = new MyPayResultListener(context);
		PayConnect.getInstance(context).pay(context, orderId, userId, price, goodsName, goodsDesc, "", mpr);		
	}
	
	static class MyPayResultListener implements PayResultListener {
		Context context = null;

		public MyPayResultListener(Context context) {
			this.context = context;
		}

		@Override
		public void onPayFinish(Context payViewContext, String order_id,
				int resultCode, String resultString, int payType, float amount,
				String goods_name) {
			if (resultCode == 0) { // 支付成功

				StringHelper.sendLongMsg(context, "您已经成功支付:" + amount
						+ "元，购买一个月的去广告服务.");
				// 支付成功时关闭当前支付界面
				PayConnect.getInstance(context).closePayView(payViewContext);
				// TODO 在客户端处理支付成功的操作
				Calendar cal = Calendar.getInstance();
				
				SharedPreferences setInfo = context.getSharedPreferences("setInfo", 0);
				Long old_time = setInfo.getLong("showAdTime", (new Date()).getTime());
				cal.setTimeInMillis(old_time);
				cal.add(Calendar.DATE, 30);
				Editor editor = setInfo.edit();
				editor.putString("showAd", "N");
				editor.putLong("showAdTime", cal.getTimeInMillis());
				editor.commit();
				// 未指定notifyUrl的情况下，交易成功后，必须发送回执
				PayConnect.getInstance(context).confirm(order_id, payType);
			} else {// 支付失败
				StringHelper.sendLongMsg(context, "支付失败!");
			}

		}

	}
	
	
	public static boolean checkShowAd(Context context){
		long now = (new Date()).getTime();
		
		SharedPreferences setInfo = context.getSharedPreferences("setInfo", 0);
		Long pay_time = setInfo.getLong("showAdTime", (new Date()).getTime());
		String showAd = setInfo.getString("showAd", "Y");
		if(now<=pay_time&&showAd.equals("N")){
			return false;
		}	
		return true;
	}
	
}
